package com.hot12345.common.spring;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.hot12345.common.util.ServletUtils;

public class SpringAbstractController {
	public final static int pageDefaultSize = 20;//默认每页大小 、原值为 20
	public final static int pageMaxSize = 50;//每页最多50条记录
	private final static Log logger = LogFactory.getLog(SpringAbstractController.class);
	
	/**
	 * 设置和初始化开始页号和每页最大记录数
	 * @param req
	 * @param modelMap
	 */
	public void pageBefore(HttpServletRequest req,ModelMap modelMap) {
		String pageNo = req.getParameter("pageNo");
		modelMap.put("pageNo", 1);
		int pn = 1;
		if(pageNo!=null && !"".equals(pageNo)){
			try{
				pn = Integer.valueOf(pageNo);
			}catch(Exception e){
				logger.error("处理分页起始号异常：",e);
			}
			if(pn<=0){
				pn = 1;
			}
			modelMap.put("pageNo", pn);
		}
	
		String pageSize = req.getParameter("pageSize");
		if(modelMap.get("pageSize")==null){
			modelMap.put("pageSize", pageDefaultSize);
			
			if(pageSize!=null && !"".equals(pageSize.trim())){
				int ps = pageDefaultSize;
				try{
					ps = Integer.valueOf(pageSize);
				}catch(Exception e){
					logger.error("处理分页每页最大数异常：",e);
				}
				if(ps>pageMaxSize || ps<1){
					ps = pageDefaultSize;
				}
				modelMap.put("pageSize", ps);
			}
		} 
		
		pn = (pn-1)*((Integer)modelMap.get("pageSize"));
		modelMap.put("startNo", pn);
		
	}
	
	/**
	 * 得到总记录数后进行最后的分布处理
	 * @param req
	 * @param totalNum 总记录数
	 * @param modelMap
	 * @author 吴宗宝
	 * @创建时间 2011-9-23 下午03:30:40
	 */
	public void pageAfter(HttpServletRequest req,long totalNum,ModelMap modelMap){
//		String pageNo = req.getParameter("pageNo");	
		//将提交到参数解释到Map中，遍历Map生成查询串。
		Map<String,String> serachParams = ServletUtils.setValuesToMap(req);
		Iterator iter = serachParams.entrySet().iterator();
		StringBuffer sb = new StringBuffer();
		while (iter.hasNext()) {
		    Map.Entry entry = (Map.Entry) iter.next();
		    Object key = entry.getKey();
		    Object val = entry.getValue();
		    if(!"pageNo".equals(key)){//去掉页号参数(页号参数在页面上已经有,如果是搜索页，直接req.getQueryString()的话会将当前页号重复加入到下一页的条件中)
		    	sb.append("&" + key+"=" + val);
		    }
		}
		
		String searchStr = sb.toString();
		modelMap.put("params", searchStr);
//		modelMap.put("params",req.getQueryString());//取URL参数直接req.getQueryString()即可，但搜索会出现重复的pageNo参数。

		//计算总页数
		int pageSize = modelMap.get("pageSize")==null?pageDefaultSize:(Integer)modelMap.get("pageSize");
		int totalPage = 0;
		if(totalNum/pageSize!=0){
			if(totalNum%pageSize!=0){
				totalPage = (int)totalNum/pageSize + 1;
			} else {
				totalPage = (int)totalNum/pageSize;
			}
		} else if(totalNum%pageSize==0){
			totalPage = (int)totalNum/pageSize;
		}
		if(totalNum==0){
			totalPage = 1;
		}
		
		modelMap.put("totalNum", totalNum);//总记录数
		modelMap.put("totalPageNum", totalPage);//总页数
		modelMap.put("URL",req.getRequestURL());
		
	}

	public int getPageMaxSize() {
		return pageMaxSize;
	}
	
	/**
	* @throws IOException 
	 * @throws IOException 
	*/
	public void printMsg(HttpServletResponse response,Object msg) {
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		try {
			response.getWriter().print(msg);
		} catch (IOException e) {
			logger.error("IOException",e);
		}
	}
	
	/**
	 * 简单封装起始号
	 * @param modelMap
	 * @return
	 * @author 吴宗宝
	 * @创建时间 2011-9-23 下午03:41:02
	 */
	public int getStartNo(ModelMap modelMap){
		if(modelMap!=null){
			return (Integer) modelMap.get("startNo");
		}
		return 0;
	}
	
	public int getPageSize(ModelMap modelMap){
		if(modelMap!=null){
			return (Integer) modelMap.get("pageSize");
		}
		return pageDefaultSize;
	}
	@InitBinder
	public void InitBinder(WebDataBinder dataBinder){
		dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));
	}
	
	/**
	 * 计算酒店企业的星级
	 * 可能其他类型企业不需要
	 * @param star
	 * @return
	 */	
	public int startCount(int star){
		if(star==0 || star==1){
			return star;
		}
		int k = star/2;
		int h = star%2;
		int ret = 0;
		if(h==0){
			ret = k;
		} else {
			ret = k+h;
		}
		return ret;
	}
	
	/** 
	 * 404重定向方法 跳转到/error/404.jsp
	 * @param request 
	 * @param response
	 * @param msg 提示信息
	 * @throws ServletException
	 * @throws IOException
	 */
	public void forward404(HttpServletRequest request,HttpServletResponse response,String msg) throws ServletException, IOException{
		request.setAttribute("error", msg);
		request.getRequestDispatcher("/error/404.jsp").forward(request,
				response);
	}
	
	public ModelAndView redirect404(String msg) throws ServletException, IOException{
		return new ModelAndView(new RedirectView("/error/404.jsp"),"error",msg);
	}
}
